package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.Announcement;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.AnnouncementService;
import com.xuanzheng.company.service.impl.AnnouncementServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/api/announcements")
public class GetAnnouncementsServlet extends HttpServlet {
    
    private final AnnouncementService announcementService = new AnnouncementServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Gson gson = new Gson();
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前用户
        HttpSession session = req.getSession();
        User currentUser = (User) session.getAttribute("user");
        
        if (currentUser == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            out.print(gson.toJson(result));
            return;
        }
        
        // 获取用户所在公司的公告
        String companyId = currentUser.getCompanyId();
        if (companyId == null || companyId.isEmpty()) {
            result.put("success", false);
            result.put("message", "用户未加入任何公司");
            out.print(gson.toJson(result));
            return;
        }
        
        try {
            List<Announcement> announcements = announcementService.getAnnouncementsByCompanyId(companyId);
            result.put("success", true);
            result.put("data", announcements);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取公告失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        out.print(gson.toJson(result));
    }
} 